﻿using System.IO;
using Ionic.Zip;
using System.Globalization;

namespace NazTek.Extension.Clr4
{
    /// <summary>
    /// Extends DirectoryInfo
    /// </summary>
    public static class DirectoryInfoExtension
    {
        /// <summary>
        /// Recursively compresses a directory's files and folders.
        /// </summary>
        /// <param name="directory">Directory whose files and folders are to be compressed</param>
        /// <param name="compressedFileName">Qualified name of the target compressed file.  Folder name is used as the filename and it's parent folder is used as path, when unspecified.</param>
        /// <returns>The compressed file containing the complete folder hierarchy and files</returns>
        /// <example><code>myDirectory.Compress(); //myDirectory is an instance of type DirectoryInfo</code></example>
        public static FileInfo Compress(this DirectoryInfo directory, string compressedFileName = null)
        {
            if (!Parameter.IsValid(compressedFileName))
                compressedFileName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", directory.FullName.TrimEnd('\\'), StringResource.Default.Cst_ZipFileExtension);
            using (ZipFile compressedFile = new ZipFile())
            {
                compressedFile.AddDirectory(directory.FullName);
                compressedFile.Save(compressedFileName);
            }
            return new FileInfo(compressedFileName);
        }
        /// <summary>
        /// Ensures the specified directory exists.
        /// </summary>
        /// <param name="directoryInfo">The directory to check for existance.</param>
        public static void EnsureExists(this DirectoryInfo directoryInfo)
        {
            directoryInfo.Parent.EnsureExists(directoryInfo.Name);
        }
        /// <summary>
        /// Ensures the specified directory as well as the specified subdirectory exists.
        /// </summary>
        /// <param name="directoryInfo">The directory to check for existance.</param>
        /// <param name="subDirectoryName">The subdirectory to check for existance within the specified directory.</param>
        private static void EnsureExists(this DirectoryInfo directoryInfo, string subDirectoryName)
        {
            if (!directoryInfo.Exists)
                directoryInfo.Parent.EnsureExists(directoryInfo.Name);
            if (directoryInfo.GetDirectories(subDirectoryName).Length == 0)
                directoryInfo.CreateSubdirectory(subDirectoryName);
        }
    }
}